package com.fh.shop.api.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
    public static String postCode(String url, Map<String,String> headMap,Map<String,String> paramMap){
        CloseableHttpClient client = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        try {
            //创建浏览器
            client = HttpClientBuilder.create().build();

            //请求地址
            httpPost = new HttpPost(url);

            //请求头
            if (headMap != null && headMap.size() > 0){
                HttpPost finalHttpPost = httpPost;
                headMap.forEach((x, y) -> finalHttpPost.addHeader(x,y));
            }

            //传递参数
            if (paramMap != null & paramMap.size() > 0){
                List<NameValuePair> list = new ArrayList<>();
                paramMap.forEach((x,y) -> list.add(new BasicNameValuePair(x,y)));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");
                httpPost.setEntity(entity);
            }

            //获得response
            response = client.execute(httpPost);

            //获得内容
            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpPost != null){
                httpPost.releaseConnection();
            }
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
